//  this library.
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/view_util.dart';

/// 购买页面搜索输入框方法
class SearchWidget extends StatefulWidget {
  /// 提示文字
  final String hint;

  /// 内容变化的回调
  final ValueChanged<String>? onChanged;

  const SearchWidget({super.key, this.hint = "搜索关键字", this.onChanged});

  @override
  State<SearchWidget> createState() => _SearchWidgetState();
}

class _SearchWidgetState extends State<SearchWidget> {
  /// 是否是输入模式，默认为false,收缩模式
  late bool _inputState;

  /// Text编辑控制器
  final TextEditingController _controller = TextEditingController();

  /// 显示图标
  get _icon => SvgPicture.asset(
    "images/package/package_search_icon.svg",
    width: 30,
    height: 30,
  );

  /// 搜索输入框
  get _textField => _inputState
      ? TextField(
    controller: _controller,
    onChanged: _onChange,
    // 自动获取焦点
    // autofocus: true,
    // 设置光标颜色
    cursorColor: colorBlue1,
    cursorHeight: 30,
    style: FontUtil.fontGrey5(2),
    decoration: InputDecoration(
      // 去掉textField自定的高度
        isCollapsed: true,
        contentPadding: EdgeInsets.only(bottom: 3),
        // 去掉下划线
        border: InputBorder.none,
        hintText: widget.hint,
        hintStyle: FontUtil.fontGrey5(2)),
  )
      : Container(
    padding: EdgeInsets.only(bottom: 4),
    child: Text(
      widget.hint,
      style: FontUtil.fontGrey5(2),
    ),
  );

  /// 返回按钮
  get _back => _inputState
      ? GestureDetector(
    onTap: () {
      setState(() {
        _inputState = false;
      });
      if (widget.onChanged != null) {
        widget.onChanged!("");
      }
      _controller.clear();
    },
    child: Icon(
      Icons.close,
      size: 30,
      color: colorGrey5,
    ),
  )
      : const SizedBox();

  @override
  void initState() {
    super.initState();
    _inputState = false;
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (!_inputState) {
          setState(() {
            _inputState = true;
          });
        }
      },
      child: Container(
        height: 56,
        width: _inputState ? 538 : 218,
        padding: EdgeInsets.symmetric(vertical: 8, horizontal: 17),
        decoration: BoxDecoration(
          color: _inputState ? colorWhite1 : colorWhite2,
          borderRadius: BorderRadius.all(Radius.circular(2)),
          border:
          _inputState ? Border.all(color: colorBlue1, width: 1) : null,
        ),
        child: Row(
          children: [
            _icon,
            hiSpace(width: 10),
            Expanded(child: _textField),
            hiSpace(width: _inputState ? 10 : 0),
            _back,
          ],
        ),
      ),
    );
  }

  /// 输入框内容变化方法
  _onChange(String value) {
    if (widget.onChanged != null) {
      widget.onChanged!(value);
    }
  }
}
